//
//  UPCalendarPicker.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/26.
//

#import "UPCalendarPicker.h"

@interface UPCalendarPicker () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIView *columnsContainer;

@property (nonatomic, strong) UILabel *dayTitleLabel;
@property (nonatomic, strong) UILabel *monthTitleLabel;
@property (nonatomic, strong) UILabel *yearTitleLabel;

@property (nonatomic, strong) UICollectionView *dayColumn;
@property (nonatomic, strong) UICollectionView *monthColumn;
@property (nonatomic, strong) UICollectionView *yearColumn;

@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UIView *separator1;
@property (nonatomic, strong) UIView *separator2;

@property (nonatomic, strong) NSArray<NSNumber *> *years;
@property (nonatomic, strong) NSArray<NSNumber *> *months;
@property (nonatomic, strong) NSArray<NSNumber *> *days;

@property (nonatomic, assign) NSInteger selectedYear;
@property (nonatomic, assign) NSInteger selectedMonth;
@property (nonatomic, assign) NSInteger selectedDay;

@end

@implementation UPCalendarPicker

- (instancetype)initWithSelectedDate:(NSDate *)selectedDate {
    self = [super init];
    if (self) {
        _selectedDate = selectedDate;
        [self setupData];
        [self setupUI];
    }
    return self;
}

- (void)setupData {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self.selectedDate];
    
    _selectedYear = components.year ?: 1990;
    _selectedMonth = components.month ?: 1;
    _selectedDay = components.day ?: 1;
    
    NSInteger currentYear = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
    NSMutableArray *yearsArray = [NSMutableArray array];
    for (NSInteger year = currentYear - 120; year <= currentYear; year++) {
        [yearsArray addObject:@(year)];
    }
    _years = [yearsArray copy];
    
    NSMutableArray *monthsArray = [NSMutableArray array];
    for (NSInteger month = 1; month <= 12; month++) {
        [monthsArray addObject:@(month)];
    }
    _months = [monthsArray copy];
    
    [self updateDays];
}

- (void)updateDays {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.year = self.selectedYear;
    components.month = self.selectedMonth;
    
    NSDate *date = [calendar dateFromComponents:components];
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    
    NSMutableArray *daysArray = [NSMutableArray array];
    for (NSInteger day = range.location; day < NSMaxRange(range); day++) {
        [daysArray addObject:@(day)];
    }
    _days = [daysArray copy];
    
    if (self.selectedDay > self.days.count) {
        self.selectedDay = self.days.count;
    }
    
    [self.dayColumn reloadData];
}

- (void)setupUI {
    [self addSubview:self.containerView];
    [self.containerView addSubview:self.titleLabel];
    [self.containerView addSubview:self.columnsContainer];
    [self.containerView addSubview:self.confirmButton];
    
    [self.columnsContainer addSubview:self.dayTitleLabel];
    [self.columnsContainer addSubview:self.monthTitleLabel];
    [self.columnsContainer addSubview:self.yearTitleLabel];
    
    [self.columnsContainer addSubview:self.dayColumn];
    [self.columnsContainer addSubview:self.separator1];
    [self.columnsContainer addSubview:self.monthColumn];
    [self.columnsContainer addSubview:self.separator2];
    [self.columnsContainer addSubview:self.yearColumn];
    
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.containerView).offset(16);
        make.leading.trailing.equalTo(self.containerView).inset(16);
    }];
    
    [self.columnsContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(16);
        make.leading.trailing.equalTo(self.containerView).inset(16);
        make.height.equalTo(@350);
    }];
    
    [self.dayTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.columnsContainer);
        make.leading.equalTo(self.columnsContainer);
        make.width.equalTo(self.columnsContainer).multipliedBy(0.3);
        make.height.equalTo(@30);
    }];
    
    [self.monthTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.columnsContainer);
        make.leading.equalTo(self.dayTitleLabel.mas_trailing);
        make.width.equalTo(self.columnsContainer).multipliedBy(0.3);
        make.height.equalTo(@30);
    }];
    
    [self.yearTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.columnsContainer);
        make.trailing.equalTo(self.columnsContainer);
        make.width.equalTo(self.columnsContainer).multipliedBy(0.3);
        make.height.equalTo(@30);
    }];
    
    [self.dayColumn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.dayTitleLabel.mas_bottom).offset(10);
        make.bottom.leading.equalTo(self.columnsContainer);
        make.width.equalTo(self.columnsContainer).multipliedBy(0.3);
    }];
    
    [self.separator1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.dayTitleLabel.mas_bottom).offset(10);
        make.bottom.equalTo(self.columnsContainer);
        make.leading.equalTo(self.dayColumn.mas_trailing);
        make.width.equalTo(@1);
    }];
    
    [self.monthColumn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.monthTitleLabel.mas_bottom).offset(10);
        make.bottom.equalTo(self.columnsContainer);
        make.leading.equalTo(self.separator1.mas_trailing);
        make.width.equalTo(self.columnsContainer).multipliedBy(0.3);
    }];
    
    [self.separator2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.yearTitleLabel.mas_bottom).offset(10);
        make.bottom.equalTo(self.columnsContainer);
        make.leading.equalTo(self.monthColumn.mas_trailing);
        make.width.equalTo(@1);
    }];
    
    [self.yearColumn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.yearTitleLabel.mas_bottom).offset(10);
        make.bottom.trailing.equalTo(self.columnsContainer);
        make.leading.equalTo(self.separator2.mas_trailing);
    }];
    
    UIImage *buttonImage = [UIImage imageNamed:@"button_bg_style1"];
    CGFloat buttonHeight = 50.0;
    CGFloat buttonAspectRatio = buttonImage.size.width / buttonImage.size.height;
    CGFloat buttonWidth = buttonHeight * buttonAspectRatio;
    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.columnsContainer.mas_bottom).offset(20);
        make.centerX.equalTo(self.containerView);
        make.height.mas_equalTo(buttonHeight);
        make.width.mas_equalTo(buttonWidth);
        make.bottom.equalTo(self.containerView).offset(-20);
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self scrollToSelectedPositionsAnimated:NO];
    });
}

- (void)scrollToSelectedPositionsAnimated:(BOOL)animated {
    NSInteger dayIndex = [self.days indexOfObject:@(self.selectedDay)];
    if (dayIndex != NSNotFound) {
        [self.dayColumn scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:dayIndex inSection:0]
                               atScrollPosition:UICollectionViewScrollPositionCenteredVertically
                                       animated:animated];
    }
    
    [self.monthColumn scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.selectedMonth - 1 inSection:0]
                             atScrollPosition:UICollectionViewScrollPositionCenteredVertically
                                     animated:animated];
    
    NSInteger yearIndex = [self.years indexOfObject:@(self.selectedYear)];
    if (yearIndex != NSNotFound) {
        [self.yearColumn scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:yearIndex inSection:0]
                               atScrollPosition:UICollectionViewScrollPositionCenteredVertically
                                       animated:animated];
    }
}

- (void)confirmSelection {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.year = self.selectedYear;
    components.month = self.selectedMonth;
    components.day = self.selectedDay;
    
    NSDate *date = [calendar dateFromComponents:components];
    if (date) {
        self.selectedDate = date;
        if ([self.delegate respondsToSelector:@selector(calendarPicker:didSelectDate:)]) {
            [self.delegate calendarPicker:self didSelectDate:date];
        }
    }
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.yearColumn) {
        return self.years.count;
    } else if (collectionView == self.monthColumn) {
        return self.months.count;
    } else if (collectionView == self.dayColumn) {
        return self.days.count;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.yearColumn) {
        UPCalendarYearCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UPCalendarYearCell" forIndexPath:indexPath];
        NSInteger year = [self.years[indexPath.item] integerValue];
        [cell configureWithYear:year isSelected:year == self.selectedYear];
        return cell;
    } else if (collectionView == self.monthColumn) {
        UPCalendarMonthCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UPCalendarMonthCell" forIndexPath:indexPath];
        NSInteger month = [self.months[indexPath.item] integerValue];
        [cell configureWithMonth:month isSelected:month == self.selectedMonth];
        return cell;
    } else if (collectionView == self.dayColumn) {
        UPCalendarDayCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UPCalendarDayCell" forIndexPath:indexPath];
        NSInteger day = [self.days[indexPath.item] integerValue];
        [cell configureWithDay:day isSelected:day == self.selectedDay];
        return cell;
    }
    return nil;
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(collectionView.bounds.size.width, 30);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.yearColumn) {
        self.selectedYear = [self.years[indexPath.item] integerValue];
        [self updateDays];
    } else if (collectionView == self.monthColumn) {
        self.selectedMonth = [self.months[indexPath.item] integerValue];
        [self updateDays];
    } else if (collectionView == self.dayColumn) {
        self.selectedDay = [self.days[indexPath.item] integerValue];
    }
    
    [collectionView reloadData];
}

#pragma mark - Lazy Properties

- (UIView *)containerView {
    if (!_containerView) {
        _containerView = [[UIView alloc] init];
        _containerView.backgroundColor = UIColor.clearColor;
        _containerView.layer.cornerRadius = 12;
        _containerView.layer.shadowColor = UIColor.blackColor.CGColor;
        _containerView.layer.shadowOpacity = 0.1;
        _containerView.layer.shadowOffset = CGSizeMake(0, 2);
        _containerView.layer.shadowRadius = 10;
    }
    return _containerView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.text = @"Date Selection";
        _titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}

- (UIView *)columnsContainer {
    if (!_columnsContainer) {
        _columnsContainer = [[UIView alloc] init];
    }
    return _columnsContainer;
}

- (UILabel *)dayTitleLabel {
    if (!_dayTitleLabel) {
        _dayTitleLabel = [[UILabel alloc] init];
        _dayTitleLabel.text = LocalizableForKey(@"Day");
        _dayTitleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightSemibold];
        _dayTitleLabel.textAlignment = NSTextAlignmentCenter;
        _dayTitleLabel.textColor = [UIColor colorWithHexString:@"#000000"];
    }
    return _dayTitleLabel;
}

- (UILabel *)monthTitleLabel {
    if (!_monthTitleLabel) {
        _monthTitleLabel = [[UILabel alloc] init];
        _monthTitleLabel.text = LocalizableForKey(@"Month");
        _monthTitleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightSemibold];
        _monthTitleLabel.textAlignment = NSTextAlignmentCenter;
        _monthTitleLabel.textColor = [UIColor colorWithHexString:@"#000000"];
    }
    return _monthTitleLabel;
}

- (UILabel *)yearTitleLabel {
    if (!_yearTitleLabel) {
        _yearTitleLabel = [[UILabel alloc] init];
        _yearTitleLabel.text = LocalizableForKey(@"Year");
        _yearTitleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightSemibold];
        _yearTitleLabel.textAlignment = NSTextAlignmentCenter;
        _yearTitleLabel.textColor = [UIColor colorWithHexString:@"#000000"];
    }
    return _yearTitleLabel;
}

- (UICollectionView *)dayColumn {
    if (!_dayColumn) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        
        _dayColumn = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _dayColumn.backgroundColor = UIColor.clearColor;
        _dayColumn.dataSource = self;
        _dayColumn.delegate = self;
        [_dayColumn registerClass:[UPCalendarDayCell class] forCellWithReuseIdentifier:@"UPCalendarDayCell"];
        _dayColumn.showsVerticalScrollIndicator = NO;
    }
    return _dayColumn;
}

- (UICollectionView *)monthColumn {
    if (!_monthColumn) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        
        _monthColumn = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _monthColumn.backgroundColor = UIColor.clearColor;
        _monthColumn.dataSource = self;
        _monthColumn.delegate = self;
        [_monthColumn registerClass:[UPCalendarMonthCell class] forCellWithReuseIdentifier:@"UPCalendarMonthCell"];
        _monthColumn.showsVerticalScrollIndicator = NO;
    }
    return _monthColumn;
}

- (UICollectionView *)yearColumn {
    if (!_yearColumn) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        
        _yearColumn = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _yearColumn.backgroundColor = UIColor.clearColor;
        _yearColumn.dataSource = self;
        _yearColumn.delegate = self;
        [_yearColumn registerClass:[UPCalendarYearCell class] forCellWithReuseIdentifier:@"UPCalendarYearCell"];
        _yearColumn.showsVerticalScrollIndicator = NO;
    }
    return _yearColumn;
}

- (UIButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmButton setBackgroundImage:[UIImage imageNamed:@"button_bg_style1"] forState: UIControlStateNormal];
        [_confirmButton setTitle:LocalizableForKey(@"Confirm") forState:UIControlStateNormal];
        [_confirmButton setTitleColor:[UIColor colorWithHexString:@"#000000"] forState:UIControlStateNormal];
        [_confirmButton addTarget:self action:@selector(confirmSelection) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmButton;
}

- (UIView *)separator1 {
    if (!_separator1) {
        _separator1 = [[UIView alloc] init];
        _separator1.backgroundColor = UIColor.systemGray5Color;
    }
    return _separator1;
}

- (UIView *)separator2 {
    if (!_separator2) {
        _separator2 = [[UIView alloc] init];
        _separator2.backgroundColor = UIColor.systemGray5Color;
    }
    return _separator2;
}

@end
